import express from "express";
import cors from "cors";
import mysql from "mysql2/promise";
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
import morgan from "morgan";
import { v4 as uuidv4 } from "uuid";

// ES6 模块的 __dirname 替代方案
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 创建 Express 应用
const app = express();
const port = process.env.PORT || 3001;

// 创建日志目录
const LOGS_DIR = path.join(__dirname, "logs");

// 确保日志目录存在
try {
  await fs.mkdir(LOGS_DIR, { recursive: true });
  console.log(`日志目录已创建: ${LOGS_DIR}`);
} catch (err) {
  console.error(`无法创建日志目录: ${err.message}`);
}

// 中间件
app.use(cors());
app.use(express.json());
app.use(morgan("dev"));

// 请求日志中间件
app.use((req, res, next) => {
  const requestId = uuidv4();
  req.requestId = requestId;

  const logData = {
    id: requestId,
    timestamp: new Date().toISOString(),
    method: req.method,
    path: req.path,
    params: req.params,
    query: req.query,
    body: req.body,
  };

  // console.log(JSON.stringify(logData, null, 2));
  next();
});

// 响应日志中间件
app.use((req, res, next) => {
  const originalSend = res.send;
  res.send = function (body) {
    const responseLog = {
      id: req.requestId,
      timestamp: new Date().toISOString(),
      status: res.statusCode,
      body: body,
    };

    // console.log(JSON.stringify(responseLog, null, 2));

    // 将日志写入文件
    const logFilePath = path.join(LOGS_DIR, `${new Date().toISOString().split("T")[0]}.log`);
    fs.appendFile(logFilePath, JSON.stringify(responseLog) + "\n").catch(console.error);

    originalSend.call(this, body);
  };
  next();
});

import configRouter from "./routes/config.js";
import testConnRouter from "./routes/test-connection.js";
import migrateRouter from "./routes/migrate.js";
import logsRouter from "./routes/logs.js";

app.use("/api/config", configRouter);
app.use("/api/test-connection", testConnRouter);
app.use("/api/migrate", migrateRouter);
app.use("/api/logs", logsRouter);

import migrateTransactionRouter from "./routes/migrate-transaction.js";
app.use("/api/migrate/transaction", migrateTransactionRouter);

import tablesRouter from "./routes/tables.js";
app.use("/api/tables", tablesRouter);
// 启动服务器
app.listen(port, () => {
  console.log(`后端服务运行在 http://localhost:${port}`);
});
